<template>
  <view :data-theme="theme">
    <!-- 导航栏 -->
    <view class="cart_nav" style="height: 20rpx;">
      <!-- #ifndef APP-PLUS -->
      <nav-bar 
        iconColor="#fff" 
        ref="navBarRef" 
        :isBackgroundColor="false" 
        navTitle="收银台"
        :leftBtn="{
          icon: 'icon-fanhui', 
          text: '返回', 
          onClick: () => goBack() 
        }"
        :rightBtn="{
          icon: 'icon-shouye', 
          text: '首页', 
          onClick: () => goHome() 
        }"
      />
      <!-- #endif -->
    </view>

    <!-- 支付信息区域 -->
    <view class="payment-info-box">
      <view class="info-row">
        <text class="label">您还需要支付</text>
        <view class="countdown-wrapper">
          <text class="countdown-label">剩余支付时间：</text>
          <uni-countdown :show-day="false" :second="timeupSecond" @timeup="timeup" />
        </view>
      </view>
      <view class="amount">{{ paymentAmount }} 元</view>
      <view class="info-row">
        <text class="plate-number">{{ currentcarNum }} 订单金额</text>
        <text class="price">{{ attributes.serviceFee }} 元</text>
      </view>
      <view class="info-row discount-row">
        <text>会员权益减免合计</text>
        <text class="discount-price">{{ attributes.discountFee }} 元</text>
      </view>
    </view>

    <!-- 积分与优惠券区域 -->
    <view class="deduction-box">
      <!-- 积分抵扣 -->
      <view class="deduction-item">        
        <view class="left-section">
          <image class="icon" src="../../../static/tabBar/jf.png"></image>
          <view class="text-section">
            <text class="deduction-label">积分抵扣</text>
            <text class="points-info">当前可用积分：{{ originalPoints }} 积分</text>
          </view>
        </view>
        <view v-show="pointDeduction">
          <CustomCheckbox 
            v-model="isPointsChecked" 
            value="points" 
            @change="handlePointsChange"
          />
        </view>
      </view>

      <!-- 优惠券抵扣 -->
      <view class="deduction-item">        
        <view class="left-section">
          <image class="icon" src="../../../static/tabBar/yhq.png"></image>
          <view class="text-section">
            <text class="deduction-label">优惠券抵扣</text>
            <text class="coupon-tip">暂无优惠券可用</text>
          </view>
        </view>
        <view v-show="couponDeduction">
          <CustomCheckbox 
            v-model="isCouponChecked" 
            value="coupon" 
            @change="handleCouponChange"
          />
        </view>
      </view>
    </view>

    <!-- 支付方式选择 -->
    <view class="deduction-box">
      <view class="deduction-item">
        <view class="left-section">
          <image class="icon" src="../../../static/tabBar/wx.png"></image>
          <view class="text-section">
            <text class="deduction-label">微信支付</text>
            <text class="points-info">使用微信付款</text>
          </view>
        </view>
        <CustomCheckbox 
          v-model="isWechatChecked" 
          value="wechat" 
          @change="handleWechatChange"
        />
      </view>

      <view class="deduction-item">
        <view class="left-section">
          <image class="icon" src="../../../static/tabBar/yl.png"></image>
          <view class="text-section">
            <text class="deduction-label">云闪付支付</text>
            <text class="points-info">使用银联云闪付</text>
          </view>
        </view>
        <view v-show="false">
          <CustomCheckbox 
            v-model="isUnionChecked" 
            value="union" 
            @change="handleUnionChange"
          />
        </view>
      </view>
    </view>

    <!-- 停车信息区域 -->
    <view class="park-info-box">
      <view class="content"> 
        <view class="title-line">
          <image class="icon2" src="../../../static/tabBar/message.png"></image>
          <text class="title-text">停车信息</text>
        </view>
        <view class="content-bottom"> 
          <view class="content-line">
            <text class="label">入场时间：</text>
            <text class="value">{{ attributes.startTime }}</text>
          </view>
          <view class="content-line">
            <text class="label">停车时长：</text>
            <text class="value">{{ formattedServiceTime }}</text>
          </view>
          <view class="content-line">
            <text class="label">会员优惠：</text>
            <text class="value">{{ attributes.discountFee }} 元</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button @click="goBack" class="common-button">取消</button>
      <button @click="payFee" class="common-button">支付</button>
    </view>
  </view>
</template>

<script>
import { postIntegralUser } from '@/api/user.js'
import { addChargeInfo,createPayOrder,updateTcyPlatformOrderBy,freeFull } from '@/api/parking.js'
import CustomCheckbox from '@/components/CustomCheckbox/index.vue'
import { onGetPreOrder } from '@/libs/order'
import { integerOfApplet } from '@/api/user';

export default {
  components: { CustomCheckbox },
  data() {
    return {
      theme: 'default',
      paymentAmount: 0.0,        // 实付总金额
      currentcarNum: '',          // 当前车牌号
      availablePoints: 0,         // 可用积分
      pointsUsed:0,//已使用积分
      isPointsChecked: false,     // 是否启用积分抵扣
      isCouponChecked: false,     // 是否启用优惠券抵扣
      isWechatChecked: false,     // 微信支付
      isUnionChecked: false,      // 云闪付
      timeupSecond: 120,          // 倒计时时间（单位：秒）
      pointDeduction: false,      // 积分抵扣状态
      couponDeduction: false,     // 停车券抵扣状态
      attributes: {               // 订单信息
        startTime: '',            // 入场时间
        serviceTime: 0,           // 停车时长（单位：秒）
        discountFee: '',          // 优惠金额
        serviceFee: '',           // 订单金额
        parkCode: ''              // 停车场编号
      },
      memberCar: false,           // 是否是会员车辆
      ruleConfig:{} ,              //规则配置,
      pointExchangeRatio:0 ,         //积分兑换比例（积分/小时）
      pointDeductionLimit:0 ,         //单日积分抵扣上限（小时）
      nonMemberFee:  0,             // 非会员收费标准
      originalPoints:'',            // 原始积分
      outTradeNo:'',                //外部交易号,唯一
      payOrderId:'',//支付订单编号
    }
  },
  computed: {
    // 计算属性：将秒转换为时分秒格式
    formattedServiceTime() {
      const seconds = this.attributes.serviceTime || 0;
      if (seconds <= 0) return '0秒';
      
      const hours = Math.floor(seconds / 3600);
      const remainingSeconds = seconds % 3600;
      const minutes = Math.floor(remainingSeconds / 60);
      const secs = remainingSeconds % 60;
      
      let result = '';
      if (hours > 0) result += `${hours}小时`;
      if (minutes > 0) result += `${minutes}分`;
      if (secs > 0 || (hours === 0 && minutes === 0)) result += `${secs}秒`;
      
      return result;
    }
  },
  onLoad(options) {
    // 接收并解析参数
    this.memberCar = options.memberCar === 'true';
    this.currentcarNum = decodeURIComponent(options.carNum || '');
    console.log('参数this.memberCar：',this.memberCar);
    console.log('参数this.currentcarNum',this.currentcarNum);
    
    // 解析订单属性
    try {
      const parsedAttr = options.attributes 
        ? JSON.parse(decodeURIComponent(options.attributes)) 
        : { startTime: '', serviceTime: 0, discountFee: '', serviceFee: '', parkCode: '' };
      
      // 确保 serviceTime 是数字类型
      this.attributes = {
        ...parsedAttr,
        serviceTime: parseInt(parsedAttr.serviceTime, 10) || 0
      };

      this.ruleConfig = this.attributes.ruleConfig;
      console.log('规则配置：',this.ruleConfig);



      if(this.ruleConfig != null &&  this.ruleConfig != undefined &&  this.ruleConfig != 'undefined'){
        if(this.ruleConfig.pointDeduction == '1'){
        this.pointDeduction = true;
        }
        if(this.ruleConfig.couponDeduction == '1'){
          this.couponDeduction = true;
        }
        this.nonMemberFee = this.ruleConfig.nonMemberFee;
        this.pointExchangeRatio = this.ruleConfig.pointExchangeRatio;
        this.pointDeductionLimit = this.ruleConfig.pointDeductionLimit;
      }
      

    } catch (error) {
      console.error('解析订单属性失败', error);
      this.attributes = { startTime: '', serviceTime: 0, discountFee: '', serviceFee: '', parkCode: '' };
    }
    
   
    // 初始化支付金额
    this.initPaymentAmount();
    console.log('订单属性：',this.attributes);
  },
   onShow() {
    // 每次页面显示时都会执行 查询积分
    this.queryPoints();
  },
  methods: {
    // 修改用户积分
    integerOfApplet(){


      if(this.pointsUsed > 0){
        // 减少积分
        let params = {
          integral: this.availablePoints,
          account: uni.getStorageSync('phone'),
        }

        integerOfApplet(params).then(res => {
          console.log('积分操作成功：', res);
        }).catch(err => {
          console.error('积分操作失败：', err);
        });
      }else{
        console.log('用户未使用积分抵扣：');
      }


    },
    // 查询用户积分
    queryPoints() {
      postIntegralUser().then(res => {
        this.availablePoints = res.data.integral;
        console.log('积分：',this.availablePoints);
        this.originalPoints = this.availablePoints;
        if(this.originalPoints < this.pointExchangeRatio){
          this.pointDeduction = false;
        }
      }).catch(err => {
        console.error('查询积分失败', err)
        uni.showToast({ title: '查询积分失败', icon: 'none' })
      })
    },

    // 初始化支付金额
    initPaymentAmount() {
      if (this.attributes.totalFee) {
        this.paymentAmount = parseFloat(this.attributes.totalFee);
        console.log('初始支付金额：',this.paymentAmount);      
      }
    },


    handlePointsChange(isChecked) {
      // 检查是否勾选了积分兑换
      if (isChecked) {
        console.log('积分抵扣处理');
        console.log('用户原始积分：', this.originalPoints);
        console.log('积分兑换比例（积分/小时）：', this.pointExchangeRatio);
        console.log('单日积分抵扣上限（小时）：', this.pointDeductionLimit);
        console.log('当前支付金额：', this.paymentAmount);
        console.log('每小时费用：', this.nonMemberFee);

        // 计算最多可抵扣的小时数（受积分余额和单日上限限制）
        const maxDeductibleHours = Math.min(
          Math.floor(this.originalPoints / this.pointExchangeRatio), // 总积分可兑换小时
          this.pointDeductionLimit // 单日上限
        );

        console.log('最多可抵扣的小时数：', maxDeductibleHours);
        
        // 计算需要抵扣的小时数以将支付金额降至0
        // 需要抵扣的小时数 = 支付金额 / 每小时费用（向上取整）
        const hoursNeededToZero = Math.ceil(this.paymentAmount / this.nonMemberFee);

        console.log('需要抵扣的小时数：', hoursNeededToZero);
        
        // 实际抵扣小时数：取需要的小时数和最多可抵扣小时数的最小值
        const actualDeductibleHours = Math.min(maxDeductibleHours, hoursNeededToZero);
        
        // 计算实际使用的积分
        const pointsUsed = actualDeductibleHours * this.pointExchangeRatio;
        
        // 计算抵扣金额
        const deductionAmount = actualDeductibleHours * this.nonMemberFee;
        
        // 更新支付金额（确保不小于0）
        this.paymentAmount = Math.max(0, this.paymentAmount - deductionAmount).toFixed(2);
        
        // 更新可用积分
        this.availablePoints = this.originalPoints - pointsUsed;
        
        // 记录积分使用情况
        this.pointsUsed = pointsUsed;
        this.pointsExchanged = true;
        this.deductibleHours = actualDeductibleHours;
        
        console.log(`成功抵扣 ${actualDeductibleHours} 小时，使用积分 ${pointsUsed}，抵扣金额 ${deductionAmount} 元`);
        console.log(`剩余支付金额：${this.paymentAmount} 元，剩余积分：${this.availablePoints}`);
      } else {
        // 取消勾选时恢复原始状态
        this.availablePoints = this.originalPoints;
        this.initPaymentAmount();
        this.pointsUsed = 0;
        this.pointsExchanged = false;
        this.deductibleHours = 0;
      }
    },
    // 优惠券抵扣（暂无逻辑，可扩展）
    handleCouponChange(isChecked) {
      console.log('优惠券状态变更：', isChecked)
    },

    // 微信支付状态
    handleWechatChange(isChecked) {
      this.isWechatChecked = isChecked
    },

    // 云闪付支付状态（禁用状态，仅演示）
    handleUnionChange(isChecked) {
      this.isUnionChecked = isChecked
    },

    // 返回上一页
    goBack() {
      uni.navigateBack({ delta: 1 })
    },

    // 回到首页
    goHome() {
      uni.switchTab({ url: '/pages/index/index' })
    },

    // 支付逻辑（简化版，实际需对接支付接口）
    payFee() {
     
      
      console.log('参数：', this.attributes);
      console.log('支付金额：', this.paymentAmount);

      if(this.paymentAmount == 0){

        uni.showModal({
          title: '提示',
          content: '您无需支付,请问是否离场？',
          showCancel: true,
          success: (res) => {
            if (res.confirm) {
              this.notifyParkingLot();
              // 用户点击确定
              uni.redirectTo({
                url: '/pages/parking/parking_pay/index'
              });
              // 用户积分              
              this.integerOfApplet();


            } else if (res.cancel) {
              // 用户点击取消，可做其他处理（比如返回首页）
              console.log('用户取消了支付操作');
            }
          }
       
        });


      }else{

        if (!this.isWechatChecked) {
          return uni.showToast({ title: '请选择微信支付', icon: 'none' })
        }
     

      // 构建符合后端要求的请求参数
      const payOrderParams = {
        subject: this.attributes.carNo +" , " + this.attributes.parkName +" 停车场", // 商品标题--当前付款的车牌号+大运城
        body: "车牌号描述"+this.attributes.goodName, // 商品描述
        totalAmount:this.paymentAmount, //0.01 , // 支付金额--收费上限
        // totalAmount:0.01, 
        openId: uni.getStorageSync('openid'),
        createBy: uni.getStorageSync('phone'),
        channel: "WXPAY",
        orderSource: "停车费",
        orderType: "01",
        subAppId: "wx478316eb07549696",//小程序appid
        tradeType: "WX_LITE",
        carNum: this.attributes.carNo//车牌号
      };

      console.log('支付参数：', payOrderParams);

      createPayOrder(payOrderParams).then(res => {
        console.log('调起微信支付成功', res);

        const payData = JSON.parse(res.data.payData);
        this.outTradeNo = res.data.mchOrderNo;
        this.payOrderId = res.data.payOrderId;

        // 把返回的订单参数，赋值给订单表
        let params ={
          updateBy: uni.getStorageSync('phone'),
          outTradeNo: this.outTradeNo,
          payOrderId: res.data.payOrderId
        }
        console.log('更新订单表参数：', params);
        updateTcyPlatformOrderBy(params).then(res => {
          console.log('更新订单表成功', res);
       
          onGetPreOrder('WXPAY', payData).then(res => {
            console.log('下单成功', res);
          }).catch(err => {
            console.error('下单失败', err);
          });

          wx.requestPayment({
            timeStamp: payData.timeStamp,
            nonceStr: payData.nonceStr,
            package: payData.package,
            signType: payData.signType,
            paySign: payData.paySign,
            success: (res) => {
              console.log('支付成功', res);
              // 支付时间
              const orderTime = new Date().toISOString();

              // 再次更新订单表，状态改成已支付
               let params ={
                updateBy: uni.getStorageSync('phone'),
                outTradeNo: this.outTradeNo,
                status: "02"
              }
              this.updateTcyPlatformOrderBy(params);
              
              // 再把支付成功的状态更新到数据库中
              this.notifyParkingLot();

              // 停车费
              const orderSource = "停车费" + this.attributes.carNo; 
            
              // // 处理支付成功逻辑
              // uni.redirectTo({
              //   // url: '/pages/parking/pay_success/index'

              //   url: `/pages/parking/pay_success/index?orderType=${encodeURIComponent(orderSource)}&orderAmount=${encodeURIComponent(this.paymentAmount)}&orderTime=${encodeURIComponent(new Date().toISOString())}`

              // });

              // 处理支付成功逻辑
              uni.redirectTo({
                url: `/pages/parking/pay_success/index?` +
                    `orderType=${encodeURIComponent(orderSource)}&` +
                    `orderAmount=${encodeURIComponent(this.paymentAmount)}&` +
                    `orderId=${encodeURIComponent(this.payOrderId)}`
              });

              //   `orderTime=${encodeURIComponent(new Date().toISOString())}&` +



              // 更新积分
              // 用户积分              
              this.integerOfApplet();
            },
            fail: (err) => {
              console.error('支付失败', err);
            }
          });





        }).catch(err => {
          console.error('更新订单表失败', err);
        });

      }).catch(err => {
        console.error('调起微信支付失败', err);
        uni.showModal({
          title: '网络异常',
          content: `请求失败：${JSON.stringify(err)}`,
          showCancel: false
        });
      });

       }
          
    },

    // 通知车场支付结果
    notifyParkingLot() {
      // addChargeInfo({ carNo: this.currentcarNum,orderNo: this.attributes.orderNo }).then(res => {
      //   console.log('通知车场成功：', res)
      // }).catch(err => {
      //   console.error('通知车场失败：', err)
      // })
       const params ={ 
        carNo: this.currentcarNum,
        parkCode: 'p240199697'
      }
      freeFull(params).then(res => {
        console.log('全免成功：', res)
      }).catch(err => {
        console.error('全免成功：', err)
      })

    },

    // 更新订单表的支付状态
    updateTcyPlatformOrderBy(params) {
      updateTcyPlatformOrderBy(params).then(res => {
        console.log('更新订单表的支付状态为已支付，成功：', res)
      }).catch(err => {
        console.error('更新订单表的支付状态为已支付，失败：', err)
      })
    },

    // 倒计时结束
    timeup() {
      uni.showToast({ title: '支付时间已到', icon: 'none' })
      this.goBack()
    }
  }
}
</script>

<style scoped lang="scss">
/* 导航栏 */
.cart_nav {
  position: relative;
  z-index: 99;
}

/* 支付信息区域 */
.payment-info-box {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin: 20rpx;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.05);
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  font-size: 26rpx;
  color: #666;
}

.countdown-wrapper {
  display: flex;
  align-items: center;
  color: #999;
}

.amount {
  font-size: 40rpx;
  color: #FA6401;
  font-weight: bold;
  text-align: center;
  margin: 20rpx 0;
}

.discount-row {
  color: #FA6401;
}

.discount-price {
  font-weight: bold;
}

/* 积分与优惠券区域 */
.deduction-box {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin: 20rpx;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.05);
}

.deduction-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.deduction-item.disabled {
  opacity: 0.5;
  pointer-events: none;
}

.left-section {
  display: flex;
  align-items: center;
}

.icon {
  width: 72rpx;
  height: 72rpx;
  margin-right: 20rpx;
}

.text-section {
  display: flex;
  flex-direction: column;
}

.deduction-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 8rpx;
}

.points-info, .coupon-tip {
  font-size: 24rpx;
  color: #666;
}

/* 停车信息区域 */
.park-info-box {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin: 20rpx;
  box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.05);
}

.title-line {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.icon2 {
  width: 44rpx;
  height: 44rpx;
  margin-right: 8rpx;
}

.content-bottom {
  padding-left: 44rpx;
}

.content-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
  font-size: 26rpx;
  color: #666;
}

.content-line .value {
  color: #333;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 120rpx;
  background-color: #f5f5f5;
  padding-bottom: var(--safe-area-inset-bottom);
}

.common-button {
  width: 40%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #FE725C;
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  margin: 0 10rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>